﻿using ShopeeWebApi.Model.Enum;
using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace ShopeeWebApi.AmazonBase
{
    public struct FormulaResult {
        public bool Result;
        public Model.Enum.EnumIsMandatory Ship;

        public FormulaResult(bool result, EnumIsMandatory ship)
        {
            Result = result;
            Ship = ship;
        }
        public static FormulaResult Empty { get; internal set; } = Create(false, EnumIsMandatory.NONE);

        public static FormulaResult Create(bool result, EnumIsMandatory ship) {
            return new(result, ship);
        }
    }
    public class FormulaFunction
    {
        public string RuleRaw { get; }
        public string Rule { get; }
        public string Hash { get; }
        public delegate FormulaResult FuncDEL(string productType, string attribute, AttributeMapRange attributeMapRange);
        private FuncDEL Func;
        public AttributeMapTypes AttributePTDMap;
        public FormulaFunction(string RuleRaw, FuncDEL Func)
        {
            this.RuleRaw = RuleRaw;
            Rule = ClearRange(RuleRaw);
            Hash = CalcHash(Rule);
            this.Func = Func;
        }
        public FormulaResult Invoke(string productType,string attribute, AttributeMapRange attributeMapRange) => Func(productType, attribute, attributeMapRange);
        public static string CalcHash(string rule)
        {
            HashAlgorithm algorithm = SHA256.Create();
            StringBuilder sb = new();
            foreach (byte b in algorithm.ComputeHash(Encoding.UTF8.GetBytes(rule)))
                sb.Append(b.ToString("X2"));
            return sb.ToString();
        }
        private static Regex RegRangeAddress = new Regex(@"\$[\d\w\$]{1,6},");
        private static Regex RegRangeLEN = new Regex(@"LEN\(\w{1,2}\d\)");
        private static Regex RegRangeCOUNTIF = new Regex(@"COUNTIF\([^)]+\)");
        internal static string ClearRange(string ruleRaw)
        {
            return RegRangeCOUNTIF.Replace(RegRangeLEN.Replace(RegRangeAddress.Replace(ruleRaw, ""), @"LEN\(\w{1,2}\d\)"), @"COUNTIF\(.+\)");
        }       
    }
}
